package edu.fhsu.csci468;

import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;

import javax.swing.event.EventListenerList;

public class Server implements ISensorEventListener, IControlPanelEventListener
{
	
	private EventListenerList listenerList;

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		new Server();
	}
	
	public Server()
	{
		// Get control panel running.
		try
		{
		ServerSocket s = new ServerSocket(Ports.CONTROL_PANEL_PORT);
		Socket incoming = s.accept();
		ControlPanel controlPanel = new ControlPanel(incoming, this);
		(new Thread(controlPanel)).start();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
		// Get sensor server running.
		SensorServer sensorServer = new SensorServer(new Server());
		(new Thread(sensorServer)).start();
	}
	
	public void sensorEventOccurred(SensorEvent evt)
	{
		System.out.println("it happened");
	}
	
	public void controlPanelEventOccurred(ControlPanelEvent evt)
	{
		
	}
	
	
	
	public void addServerEventListener(
			IControlPanelEventListener eventListener)
	{
		listenerList.add(IControlPanelEventListener.class, eventListener);
	}

	public void removeServerEventListener(
			IServerEventListener eventListener)
	{
		listenerList.remove(IServerEventListener.class, eventListener);
	}

	public void removeAllServerEventListeners()
	{
		listenerList = new EventListenerList();
	}

	private void fireServerEvent(ServerEvent event)
	{
		Object[] listeners = listenerList.getListenerList();
		// Each listener occupies two elements - the first is the listener class
		// and the second is the listener instance
		for (int i = 0; i < listeners.length; i += 2)
		{
			if (listeners[i] == IServerEventListener.class)
			{
				((IServerEventListener) listeners[i + 1])
						.serverEventOccurred(event);
			}
		}
	}

}
